import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import './index.css';

import pageOne from '../../../public/Image/guidance_page_one.png';
import pageTwo from '../../../public/Image/guidance_page_two.png';
import pageThree from '../../../public/Image/guidance_page_three.png';
import pageFour from '../../../public/Image/guidance_page_four.png';
import pageFive from '../../../public/Image/guidance_page_five.png';

interface GuideOverlayProps {
  onFinish: () => void;
  storageKey?: string;
  autoIntervalMs?: number;
}

const GuideOverlay: React.FC<GuideOverlayProps> = ({ onFinish, storageKey = 'guide_shown', autoIntervalMs = 2500 }) => {
  const images = useMemo(() => [pageOne, pageTwo, pageThree, pageFour, pageFive], []);
  const titles = useMemo(() => [
    '丰富的健康常识',
    '海量药品信息',
    '智能症状查询',
    '专属健康档案',
    '打造你的健康常青树'
  ], []);
  const [index, setIndex] = useState<number>(0);
  const [paused, setPaused] = useState<boolean>(false);
  const timerRef = useRef<number | null>(null);

  useEffect(() => {
    const shown = localStorage.getItem(storageKey);
    if (shown === '1') {
      onFinish();
    }
  }, [onFinish, storageKey]);

  const finish = useCallback(() => {
    localStorage.setItem(storageKey, '1');
    onFinish();
  }, [onFinish, storageKey]);

  const goNext = useCallback(() => {
    setIndex((prev) => (prev < images.length - 1 ? prev + 1 : (finish(), prev)));
  }, [images.length, finish]);

  // Auto play
  useEffect(() => {
    if (paused || autoIntervalMs <= 0) return;
    timerRef.current && window.clearInterval(timerRef.current);
    timerRef.current = window.setInterval(goNext, autoIntervalMs);
    return () => {
      if (timerRef.current) {
        window.clearInterval(timerRef.current);
        timerRef.current = null;
      }
    };
  }, [goNext, autoIntervalMs, paused]);

  // Touch to pause while interacting (mobile friendly)
  const onTouchStart = () => setPaused(true);
  const onTouchEnd = () => setPaused(false);

  // Simple swipe detection
  const startX = useRef<number>(0);
  const onTouchStartSwipe = (e: React.TouchEvent<HTMLDivElement>) => {
    onTouchStart();
    startX.current = e.touches[0].clientX;
  };
  const onTouchEndSwipe = (e: React.TouchEvent<HTMLDivElement>) => {
    const endX = e.changedTouches[0].clientX;
    const delta = endX - startX.current;
    if (Math.abs(delta) > 40) {
      if (delta < 0) {
        // next
        setIndex((prev) => Math.min(prev + 1, images.length - 1));
      } else {
        // prev
        setIndex((prev) => Math.max(prev - 1, 0));
      }
    }
    onTouchEnd();
  };

  return (
    <div className="guide-overlay" aria-modal={true} role="dialog">
      <div
        className="guide-image"
        style={{ backgroundImage: `url(${images[index]})` }}
        onTouchStart={onTouchStartSwipe}
        onTouchEnd={onTouchEndSwipe}
      />

      <div className="guide-controls">
        <div className="guide-title">{titles[index]}</div>
        {index === images.length - 1 && (
          <button className="guide-enter" onClick={finish}>马上进入</button>
        )}
        <div className="guide-dots">
          {images.map((_, i) => (
            <span
              key={i}
              className={i === index ? 'dot active' : 'dot'}
              onClick={() => setIndex(i)}
            />
          ))}
        </div>
      </div>
    </div>
  );
};

export default GuideOverlay;


